-- metscrape - bulk-download weather forecasts.
-- Copyright (C) 2013  Jack Kelly <jack@jackkelly.name>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

module Scrapers.MetVUW (scrapeMetVUW) where

import Control.Exception
import Data.List
import Data.Maybe
import Prelude hiding (catch)
import Scraper
import System.IO
import Text.Printf
import Text.XML.HXT.Core
import Text.XML.HXT.HTTP

forecastURL :: String -> String
forecastURL region = ("http://www.metvuw.com/forecast/forecast1.php"
                      ++ "?type=rain&region=" ++ region ++ "&tim=06")

forecastImageURL :: String -> String -> Int -> String
forecastImageURL region date time =
    (printf "http://www.metvuw.com/forecast/%s/rain-%s-%s-%02d.gif"
            date region date time)

-- Look for the image that's the actual weather forecast.
imageDate :: [String] -> Maybe String
imageDate images = listToMaybe $ [ x | x <- images, "rain-" `isInfixOf` x ]

scrapeBase :: String -> IO (Maybe String)
scrapeBase region = do
  let url = forecastURL region
  let grabit = runX (readDocument [ withHTTP [],
                                    withParseHTML yes,
                                    withWarnings no ] url
                     //>
                     hasName "img"
                     >>>
                     getAttrValue "src")
  let get = catch grabit (\e -> do let msg = show (e :: IOException)
                                   hPutStrLn stderr ("Warning: " ++ msg)
                                   get)
  images <- get
  case imageDate images of
    Nothing -> return Nothing
    Just image -> return $ Just $ take 10 $ drop 2 $ image

scrapeMetVUW :: String -> String -> Scraper
scrapeMetVUW region pattern = IOWGet $ do
  maybeBase <- scrapeBase region
  return $ case maybeBase of
             Nothing -> []
             Just base -> [ (forecastImageURL region base n,
                             printf pattern n) | n <- [6, 12..180] ]
